package com.boge.modules.sys.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boge.common.utils.HttpClientUtil;
import com.boge.common.utils.R;
import com.boge.common.validator.ValidatorUtils;
import com.boge.common.validator.group.AddGroup;
import com.boge.modules.house.entity.TAreaEntity;
import com.boge.modules.house.entity.TCityEntity;
import com.boge.modules.house.entity.TProvinceEntity;
import com.boge.modules.house.entity.TTypeEntity;
import com.boge.modules.house.service.TAreaService;
import com.boge.modules.house.service.TCityService;
import com.boge.modules.house.service.TProvinceService;
import com.boge.modules.house.service.TTypeService;
import com.boge.modules.house.vo.Banner;
import com.boge.modules.house.vo.Nav;
import com.boge.modules.house.vo.Plan;
import com.boge.modules.house.vo.Tile;
import com.boge.modules.sys.entity.SysRoleEntity;
import com.boge.modules.sys.entity.SysUserEntity;
import com.boge.modules.sys.entity.SysUserRoleEntity;
import com.boge.modules.sys.service.SysRoleService;
import com.boge.modules.sys.service.SysUserRoleService;
import com.boge.modules.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping({"/web","home"})
public class WebController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Autowired
    private TTypeService tTypeService;

    public static final String BASE_URL = "http://localhost:8070/base-fast/file/fileController/download?fileName=";

    @GetMapping("/info")
    @ResponseBody
    public R getHomeInfo(){
        // bannerList 固定数据
        List<Banner> bannerList = new ArrayList<>();
        bannerList.add(new Banner(1,"banner1","http://localhost:6060/public/home_banner_1.jpg"));
        bannerList.add(new Banner(2,"banner2","http://localhost:6060/public/home_banner_2.jpg"));
        bannerList.add(new Banner(3,"banner3","http://localhost:6060/public/home_banner_3.jpg"));
        bannerList.add(new Banner(4,"banner4","http://localhost:6060/public/home_banner_4.jpg"));
        // navList
        List<Nav> navList = new ArrayList<>();
        // 查询所有的类别数据
        List<TTypeEntity> list = tTypeService.list();
        for (TTypeEntity entity : list) {
            navList.add(new Nav(entity.getId(),entity.getName(),BASE_URL+"/"+entity.getImg()));
        }
        // tileList
        List<Tile> tileList = new ArrayList<>();
        tileList.add(new Tile(1,"http://localhost:6060/public/home_tile_1.jpg","硅谷家服","搬家·保洁·清洁·维修"));
        tileList.add(new Tile(2,"http://localhost:6060/public/home_tile_2.jpg","硅谷智能","全屋智能家装"));
        // planList
        List<Plan> planList = new ArrayList<>();
        planList.add(new Plan(1,"http://localhost:6060/public/home_plan_1.jpg"));
        planList.add(new Plan(2,"http://localhost:6060/public/home_plan_2.jpg"));
        planList.add(new Plan(3,"http://localhost:6060/public/home_plan_3.jpg"));
        planList.add(new Plan(4,"http://localhost:6060/public/home_plan_4.jpg"));

        Map<String,Object> map = new HashMap<>();
        map.put("tileList",tileList);
        map.put("planList",planList);
        map.put("navList",navList);
        map.put("bannerList",bannerList);
        map.put("adPicture","http://localhost:6060/public/home_ad.jpg");
        return R.ok().put("message","success").put("data",map).put("code",200);
    }

    @PostMapping("/save")
    @ResponseBody
    public R save(@RequestBody SysUserEntity user){
        user.setStatus(1);
        user.setNickname(user.getUsername());
        // 绑定角色
        userService.saveUser(user);
        QueryWrapper<SysRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name","房东");
        List<SysRoleEntity> list = roleService.list(wrapper);
        if(list != null && list.size() > 0){
            SysRoleEntity sysRoleEntity = list.get(0);
            SysUserRoleEntity entity = new SysUserRoleEntity();
            entity.setUserId(user.getUserId());
            entity.setRoleId(sysRoleEntity.getRoleId());
            userRoleService.save(entity);
        }
        return R.ok();
    }




    @Autowired
    private TProvinceService provinceService;

    @Autowired
    private TCityService cityService;

    @Autowired
    private TAreaService areaService;

    // GET请求接口不带参数
    @GetMapping("/doGetNoParams")
    @ResponseBody
    public String doGetNoParams() {
        String result = HttpClientUtil.doGetNoParams();
        // 需要转换为json 数据
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getIntValue("code") == 200){
            JSONArray data = jsonObject.getJSONArray("data");
            // 循环遍历找到所有的省份数据
            for (int i = 0; i < data.size(); i++) {
                String code = data.getJSONObject(i).getString("code");
                String name = data.getJSONObject(i).getString("name");

                TProvinceEntity provinceEntity = new TProvinceEntity();
                provinceEntity.setCode(code);
                provinceEntity.setName(name);
                provinceService.save(provinceEntity);
                // 需要根据省份找到对应的城市
                String res = HttpClientUtil.doGetParams("http://localhost:6060/city?provinceCode="+code);
                JSONObject cityObject = JSONObject.parseObject(res);
                JSONArray data1 = cityObject.getJSONArray("data");
                if(cityObject.getIntValue("code") == 200){
                    for (int i1 = 0; i1 < data1.size(); i1++) {
                        String code1 = data1.getJSONObject(i1).getString("code");
                        String name1 = data1.getJSONObject(i1).getString("name");
                        TCityEntity cityEntity = new TCityEntity();
                        cityEntity.setCode(code1);
                        cityEntity.setName(name1);
                        cityEntity.setProvinceCode(code);
                        cityService.save(cityEntity);
                        // 根据城市找地区
                        String resArea = HttpClientUtil.doGetParams("http://localhost:6060/area?cityCode="+code1);

                        JSONObject areaObject = JSONObject.parseObject(resArea);
                        JSONArray data2 = areaObject.getJSONArray("data");
                        if(areaObject.getIntValue("code") == 200){
                            for (int i2 = 0; i2 < data2.size(); i2++) {
                                String code2 = data2.getJSONObject(i2).getString("code");
                                String name2 = data2.getJSONObject(i2).getString("name");
                                TAreaEntity areaEntity = new TAreaEntity();
                                areaEntity.setCode(code2);
                                areaEntity.setName(name2);
                                areaEntity.setCityCode(code1);
                                areaEntity.setPrvoinceCode(code);
                                areaService.save(areaEntity);
                            }
                        }
                    }
                }
            }
        }
        //System.out.println(result);
        return result;
    }

    //  导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        // 从数据库查询出所有的数据
        List<SysUserEntity> list=userService.list();
        //通过 工具类创建writer   写出到磁盘路径
        // 在内存操作，写出到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);
        // 自定义标题别名
//       writer.addHeaderAlias("username","用户名");
//       writer.addHeaderAlias("password","密码");
//       writer.addHeaderAlias("nikename","昵称");
//       writer.addHeaderAlias("email","邮箱");
//       writer.addHeaderAlias("phone","电话");
//       writer.addHeaderAlias("address","地址");
//       writer.addHeaderAlias("createTime","创建时间");
//       writer.addHeaderAlias("avatar","头像");
        // 一次性写出list内的对象到Excel，使用默认样式，强制输出标题
        writer.write(list);
        //  设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName= URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" +fileName+".xlsx");

        // 把writer里的东西写入到输出流里
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out);
        out.close();
        writer.close();
    }
}
